import React, { Component } from "react";
import PropTypes from "prop-types";
import {
  View,
  Image,
  StyleSheet,
  FlatList,
  ActivityIndicator,
  Platform,
  Dimensions
} from "react-native";
import Label from "../label/index";

import Font from "../../config/theme/standard/fonts";
import RefreshStates from "./RefreshStates";
import LoadStates from "./LoadStates";


export default class Pullrefresh extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isShow: true,
      changeFooter: false
    };
  }

    //回到顶部
    scrollToTop(){
      this.flatList.scrollToOffset(true,0);
    }
  

  _keyExtractor = (item, index) => {
    return "item-" + index;
  };

  _renderItem = item => {
    return this.props.renderItem(item);
  };

  _renderHeader = () => {
    let {
      header,
      refreshSucessInfo,
      refreshState,
      refreshFailtureInfo,
      refreshNoInternetInfo,
      refreshNoMoreInfo
    } = this.props;
    let { isShow } = this.state;

    if (isShow) {
      if (refreshState == RefreshStates.Normal) {
        return <View>{header ? header : null}</View>;
      } else if (refreshState == RefreshStates.RefreshSucess) {
        return (
          <View style={{ flexDirection: "column" }}>
            <View style={[styles.itemView, { justifyContent: "center" }]}>
              <Label
                text={refreshSucessInfo}
                labelStyle={{ marginLeft: 20, fontSize: Font.formFontSize }}
              />
            </View>
            {header ? header : null}
          </View>
        );
      } else {
        let info;
        if (refreshState == RefreshStates.RefreshFailure) {
          info = refreshFailtureInfo;
        } else if (refreshState == RefreshStates.NoRefreshing) {
          info = refreshNoMoreInfo;
        } else if (refreshState == RefreshStates.NoInternet) {
          info = refreshNoInternetInfo;
        } else {
          return <View />;
        }
        return (
          <View style={{ flexDirection: "column" }}>
            <View style={[styles.itemView, { justifyContent: "center" }]}>
              <Label
                text={info}
                labelStyle={{ marginLeft: 20, fontSize: Font.formFontSize }}
              />
            </View>
            {header ? header : null}
          </View>
        );
      }
    } else {
      return <View>{header ? header : null}</View>;
    }
  };

  //渲染加载图标
  _renderLoadingIcon = () => {
    if (this.props.loadingIcon) {
      return (
        <Image
          source={this.props.loadingIcon}
          style={{ width: 20, height: 20, resizeMode: "contain" }}
        />
      );
    } else {
      if (this.props.loadingDefaultIcon) {
        return <ActivityIndicator />;
      } else {
        return null;
      }
    }
  };

  _renderFooter = () => {
    let {
      loadState,
      footer,
      loadingInfo,
      loadingNoMoreInfo,
      loadingFailtureInfo
    } = this.props;
    if (loadState == LoadStates.Finish) {
      return <View>{footer ? footer : null}</View>;
    } else if (loadState == LoadStates.Loading) {
      return (
        <View style={{ flexDirection: "column" }}>
          <View style={[styles.itemView, { justifyContent: "center" }]}>
            {this._renderLoadingIcon()}
            <Label
              text={loadingInfo}
              labelStyle={{ marginLeft: 20, fontSize: Font.formFontSize }}
            />
          </View>
          {footer ? footer : null}
        </View>
      );
    } else {
      let loadInfo;
      if (loadState == LoadStates.NoMoreData) {
        loadInfo = loadingNoMoreInfo;
      } else if (loadState == LoadStates.LoadFailure) {
        loadInfo = loadingFailtureInfo;
      } else {
        return <View />;
      }
      return (
        <View style={{ flexDirection: "column" }}>
          <View style={[styles.itemView, { justifyContent: "center" }]}>
            <Label
              text={loadInfo}
              labelStyle={{ marginLeft: 20, fontSize: Font.formFontSize }}
            />
          </View>
          {footer ? footer : null}
        </View>
      );
    }
  };

  _separator = () => {
    if (this.props.separatorLine) {
      return this.props.separatorLine;
    } else {
      return null;
    }
  };

  _onLoadMore = () => {
    //若已无更多数据，则停止执行加载方法
    if (this.props.loadState == LoadStates.NoMoreData) {
      return;
    }
    if (this.props.onLoadMore) {
      //防止异步方法多次调用
      if (this.props.loadState == LoadStates.Loading) {
        return;
      } else {
        this.props.onLoadMore();
      }
    }
  };

  _onRefresh = () => {
    if (this.props.onRefresh) {
      this.props.onRefresh();
    }
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    if (('refreshState' in nextProps) && (
        nextProps.refreshState == RefreshStates.RefreshSucess ||
        nextProps.refreshState == RefreshStates.RefreshFailure ||
        nextProps.refreshState == RefreshStates.NoInternet ||
        nextProps.refreshState == RefreshStates.NoRefreshing
    )) {
        return {
            isShow: true,
        };
    }
    return null;
  }

  componentDidUpdate(){
    this.timer = setTimeout(() => {
      this.setState({ isShow: false });
    }, 1000);
  }


  componentWillUnmount() {
    clearTimeout(this.timer);
  }

  render() {

    let { header, data, footer, refreshState, viewHeight ,contentContainerStyle , showScrollbar } = this.props;
    let headerComponent = this._renderHeader();
    let footerComponent = this._renderFooter();
    return (
      <View style={{ height: viewHeight }}>
        <FlatList
        ref={(c)=>this.flatList=c}
          ListHeaderComponent={headerComponent}
          ListFooterComponent={footerComponent}
          ItemSeparatorComponent={this._separator}
          renderItem={this._renderItem}
          data={data}
          onRefresh={this._onRefresh}
          refreshing={refreshState == 1 ? true : false}
          keyExtractor={this._keyExtractor}
          onEndReachedThreshold={Platform.OS == "ios" ? -0.1 : 0.1}
          onEndReached={this._onLoadMore}
          initialNumToRender={10}
          showsVerticalScrollIndicator={showScrollbar}
          contentContainerStyle={contentContainerStyle}
        />
      </View>
    );
  }
}

Pullrefresh.propTypes = {
  //数据
  data: PropTypes.array.isRequired,
  //自定义顶部内容
  header: PropTypes.any,
  //自定义底部内容
  footer: PropTypes.any,
  //自定义分割线内容
  separatorLine: PropTypes.any,
  //自定义每一项内容
  renderItem: PropTypes.func,
  //显示区域高度
  viewHeight: PropTypes.number,

  //下拉刷新状态
  refreshState: PropTypes.number,
  //下拉刷新回调函数
  onRefresh: PropTypes.func,
  //刷新成功提示语
  refreshSucessInfo: PropTypes.string,
  //刷新失败提示语
  refreshFailtureInfo: PropTypes.string,
  //暂无更新提示语
  refreshNoMoreInfo: PropTypes.string,
  //刷新无网络连接提示语
  refreshNoInternetInfo: PropTypes.string,

  //底部上拉加载状态
  loadState: PropTypes.number,
  //底部上拉加载更多回调函数
  onLoadMore: PropTypes.func,
  //底部正在加载提示语
  loadingInfo: PropTypes.string,
  //是否显示底部正在加载默认图标（菊花图标）
  loadingDefaultIcon: PropTypes.bool,
  //底部正在加载Icon
  loadingIcon: PropTypes.any,
  //底部无更多数据提示语
  loadingNoMoreInfo: PropTypes.string,
  //底部加载失败提示语
  loadingFailtureInfo: PropTypes.string,
   //内容区域容器样式
   contentContainerStyle: PropTypes.any,
   //是否显示滚动条
  showScrollbar: PropTypes.bool,
};

Pullrefresh.defaultProps = {
  viewHeight: Dimensions.get('window').height,
  showScrollbar: true,

  loadState: LoadStates.Finish,
  loadingInfo: "正在加载...",
  loadingNoMoreInfo: "没有更多了...",
  loadingFailtureInfo: "加载失败...",
  loadingDefaultIcon: true,

  refreshState: RefreshStates.Normal,
  refreshSucessInfo: "更新成功",
  refreshFailtureInfo: "更新出错，请稍后再试！",
  refreshNoMoreInfo: "暂无更新，请休息一会！",
  refreshNoInternetInfo: "网络连接失败，请稍后再试！"
};

const styles = StyleSheet.create({
  itemView: {
    flexDirection: "row",
    justifyContent: "flex-start",
    height: 40,
    alignItems: "center"
  },
  loadView: {
    flexDirection: "column"
  },
  item: {
    marginLeft: 20,
    marginRight: 20
  }
});
